package ru.sviridov.sellandbuy.json;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONResolver implements Serializable{
	private static final long serialVersionUID = 8124293579912963666L;
	
	private int errorCode=-1;
	private String errorMessage;
	private String sessionId=null;

	private List<Object> results;
	
	public JSONResolver(String jSONString){
		results = parse(jSONString,null);
	}
	
	public JSONResolver(String jSONString,JSONParser parser){
		Log.i("SERVICE", "RESPONSE: "+jSONString);
//		results = parse(jSONString,parser);
	}
	
	private List<Object> parse(String jSONString, JSONParser parser){
		List<Object> resObjs = new ArrayList<Object>(0);
		try {
			JSONObject json = new JSONObject(jSONString);
			sessionId = json.isNull("session_id") ? null:json.getString("session_id");
			errorCode = json.optInt("errorCode");
			if(errorCode!=JSONErrorCode.OK) {
				if(errorCode==JSONErrorCode.UNAUTHORIZED)
					errorMessage = "������ ������� �������."; 
				else
					errorMessage = json.optString("errorMessage");
				return resObjs;
			}
			
			if(parser!=null)
				resObjs = parser.parseResult(json);
			else
				resObjs = new StandardParser().parseResult(json);
		} catch (JSONException e) {
			e.printStackTrace();
			errorCode = -1;
			errorMessage = e.getMessage();
		}
		
		return resObjs;
	}
	
	/**return JSONErrorCode*/
	public int getErrorCode() {
		return errorCode;
	}
	
	public String getErrorMessage() {
		return errorMessage;
	}
	
	public int count(){
		return results.size();
	}
	
	public Object getResult(int position){
		if(position<results.size() && position>=0)
			return results.get(position);
		
		return null;
	}

	public List<Object> getAllResults(){
		return results;
	}
	
	public String getSessionId() {
		return sessionId;
	}
			
}
